﻿using BoardBroker;
using ComLib.ComType;
using CoreBroker;
using KWindow.KPageCore;
using KXmlUIControl;
using LogLib;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace IPCPages
{
    public class Uninstaller
    {
        private List<XmlProgramObject> Programs = null;
        private Dictionary<string, Process> _dicPrograms = new Dictionary<string, Process>();
        private string MotionControlName = "LedDemo";
        private string DeviceManagerName = "DeviceManager";
        private string PhotoUploaderName = "PhotoUploader";
        private string PhotoProcessorName = "KProcessor";
        private string PhotoPrinterName = "KPhotoPrinter";
        private string KeyBoardManagerName = "KeyboardManager";

        public Uninstaller(List<XmlProgramObject> configs, Dictionary<string, Process> dic)
        {
            Programs = configs;
            _dicPrograms = dic;
        }

        public void Run(IntPtr hWnd)
        {
            CloseDeviceControl();
            CloseDeviceManager();
            ClosePhotoUploader();
            ClosePhotoProcessor();
            ClosePhotoPrinter();
            CloseKeyBoardManager(hWnd);
            KillProcess();
        }

        /// <summary>
        /// 强制关闭某些应用程序
        /// </summary>
        private void KillProcess()
        {
            List<Process> listPrograms = _dicPrograms.Values.ToList();
            foreach (Process p in listPrograms)
            {
                string pName = _dicPrograms.FirstOrDefault(q => q.Value == p).Key;
                if (string.IsNullOrEmpty(pName))
                {
                    continue;
                }
                XmlProgramObject config = Programs.Find(r => r.Name.Equals(pName));
                if (config == null)
                {
                    continue;
                }
                try
                {
                    if (config.ForcingClosed)
                    {
                        if(!p.HasExited)
                        {
                            p.Kill();
                        }                       
                    }
                }
                catch (Exception ex)
                {
                    Log.WriteException(ex.ToString());
                }
            }
        }

        private void CloseDeviceControl()
        {
            if (!_dicPrograms.ContainsKey(MotionControlName))
            {
                return;
            }
            Process p = _dicPrograms[MotionControlName];
            if (p.HasExited)
            {
                return;
            }
            BoardControl motion = BoardControl.Instance;
            motion.CloseDevice();
        }

        private void CloseDeviceManager()
        {
            if (!_dicPrograms.ContainsKey(DeviceManagerName))
            {
                return;
            }
            Process p = _dicPrograms[DeviceManagerName];
            if (p.HasExited)
            {
                return;
            }
            DeviceControl device = new DeviceControl("IDCardReader");
            device.Init();
            device.ExitApp();
        }

        private void ClosePhotoUploader()
        {
            if (!_dicPrograms.ContainsKey(PhotoUploaderName))
            {
                return;
            }
            Process p = _dicPrograms[PhotoUploaderName];
            if (p.HasExited)
            {
                return;
            }
            TransferControl transfer = new TransferControl("FTPService");
            transfer.Init();
            transfer.ExitApp();
        }

        private void ClosePhotoPrinter()
        {
            if (!_dicPrograms.ContainsKey(PhotoPrinterName))
            {
                return;
            }
            Process p = _dicPrograms[PhotoPrinterName];
            if (p.HasExited)
            {
                return;
            }
            PrintControl printApp = new PrintControl("FRPrinter");
            printApp.Init();
            printApp.ExitApp();
        }

        private void ClosePhotoProcessor()
        {
            if (!_dicPrograms.ContainsKey(PhotoProcessorName))
            {
                return;
            }
            Process p = _dicPrograms[PhotoProcessorName];
            if (p.HasExited)
            {
                return;
            }
            try
            {
                DetectRequestArgs RequestArgs = new DetectRequestArgs();
                RequestArgs.App = ApplyTo.ExitAndEntry;
                RequestArgs.Index = 0;
                RequestArgs.Method = DetectProcessMethods.ExitApp;
                RequestArgs.PhotoName = "";
                string jsonRequestString = JsonConvert.SerializeObject(RequestArgs);
                PhotoDetectClient client = new PhotoDetectClient("test_pipe", ".");
                string reponseString = client.Request(jsonRequestString);
                Log.WriteAsync("收到服务器返回信息:" + reponseString);
            }
            catch (Exception ex)
            {
                Log.WriteException(ex.ToString());
            }    
        }

        public void CloseKeyBoardManager(IntPtr hWnd)
        {
            if (!_dicPrograms.ContainsKey(KeyBoardManagerName))
            {
                return;
            }
            //PageControlBase.CloseKeyBoardManager(hWnd);
        }
    }
}
